package com.lablzh.gdxy.controller;

import com.lablzh.gdxy.component.JwtTokenUtil;
import com.lablzh.gdxy.component.POIUtil;
import com.lablzh.gdxy.entity.admin.Material;
import com.lablzh.gdxy.entity.admin.News;

import com.lablzh.gdxy.entity.course.Course;
import com.lablzh.gdxy.repository.admin.NewsRepository;
import com.lablzh.gdxy.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;

import com.lablzh.gdxy.repository.admin.NewsRepository;
import com.lablzh.gdxy.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private POIUtil poiUtil;
    @Autowired
    private NewsRepository newsRepository;


    /**
     * 分页查询新闻
     * @param page
     * @return
     */
    @GetMapping("/newsByPage")
    public Map<String,Object> getAllNewsByPage(@RequestParam(name = "page", defaultValue = "0") int page) {

        Pageable pageable= PageRequest.of(page - 1,20, Sort.by(Sort.Direction.DESC,"id"));
        Page<News> all=newsRepository.findAll(pageable);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("practice", all.getContent());
        return data;

    }



    @GetMapping("/downloadFile")
    public void downloadFile(@PathParam("filename") String filename,
                             HttpServletRequest request,
                             HttpServletResponse response) throws FileNotFoundException {
        fileService.downloadFile(filename, request, response);
    }

    //    @PostMapping("/uploadFile")
//    public Map<String ,String> uploadFile(@RequestParam("file") MultipartFile file,
//                                          HttpServletRequest res) throws IOException {
//        String headerToken = res.getHeader("Authorization");
//        String token = headerToken.replace("Bearer", "").trim();
//        String username=jwtTokenUtil.getUsernameFromToken(token);
//        return fileService.uploadFile(file,res,username);
//    }

    @PostMapping("/summitFile")
    public Map<String, String> summitFile(@RequestParam("file") MultipartFile file,
                                          HttpServletRequest res) throws IOException {
        return fileService.summitFile(res, "生产实习", 2);
    }

    /**
     * 下载上传的毕设报告
     * @param category
     * @param id
     * @param filename
     * @param request
     * @param response
     * @throws FileNotFoundException
     */
    @GetMapping("/downloadReport")
    public void downloadReport(@RequestParam("category") String category,
                               @RequestParam("ID") Integer id,
                               @RequestParam("filename") String filename,
                               HttpServletRequest request,
                               HttpServletResponse response) throws FileNotFoundException {
        fileService.reviewFile(category, id, filename, request, response);
    }

    /**
     * 添加资料下载
     *
     * @param request
     * @return
     * @throws Exception
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @PostMapping("/material")
    public String addMaterial(HttpServletRequest request) throws Exception {
        String columns = request.getParameter("columns");
        String category = request.getParameter("category");
        return fileService.addMaterial(request, columns, category);
    }

    /**
     * 删除资料下载
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @DeleteMapping("/material")
    public String deleteMaterial(@RequestParam("ID") Integer id) {
        return fileService.deleteMaterial(id);
    }

    /**
     * 获取所有资料下载
     * @return
     */
    @GetMapping("/material")
    public List<Material> getAllMaterial() {
        return fileService.getAllMaterial();
    }

    /**
     * 分页且分类获取材料
     * @param page
     * @param limit
     * @param column
     * @return
     */
    @GetMapping("/materialPage")
    public Map getAllMaterial(@RequestParam("page") Integer page,
                                         @RequestParam("limit") Integer limit,
                                         @RequestParam("column") String column) {
        return fileService.getAllMaterial(page, limit, column);
    }

    /**
     * 添加新闻
     * @param news
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @PostMapping("/news")
    public String addNews(@RequestBody News news) {
        return fileService.addNews(news);
    }

    /**
     * 修改新闻
     *
     * @param news
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @PutMapping("/news")
    public String updateNews(@RequestBody News news) {
        return fileService.updateNews(news);
    }

    /**
     * 获取所有新闻
     *
     * @return
     */
    @GetMapping("/news")
    public List<News> getAllNews() {
        return fileService.getAllNews();
    }
    /**
     *
     *分页展示新闻
     * @return
     */
    @GetMapping("/newsByPart")
    public Map<String, Object> newsByPart(@RequestParam("limit")Integer limit,
                                          @RequestParam("page")Integer page,
                                          @RequestParam("columns")String columns,
                                          @RequestParam("category") String category) {

      //  Example<Course> example = Example.of(course);
        News news=new News();
        news.setColumns(columns);
        news.setCategory(category);
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("columns", ExampleMatcher.GenericPropertyMatchers.contains())
                .withMatcher("category", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<News> example = Example.of(news, exampleMatcher);
        Pageable designPage = PageRequest.of(page-1, limit, Sort.by(Sort.Direction.DESC, "id"));
            Page<News> all = newsRepository.findAll(example,designPage);
            Map<String, Object> data = new HashMap<>();
            data.put("totalPage", all.getTotalPages());
            data.put("total", all.getTotalElements());
            data.put("list", all.getContent());
            return data;
    }
    /**
     *
     *分类展示新闻（5条）
     * @return
     */
    @GetMapping("/newsBySubject")
    public Map<String, Object> newsByPart(@RequestParam("subject")String subject) {

        //  Example<Course> example = Example.of(course);
        News news=new News();
        news.setSubject(subject);

        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                .withMatcher("subject", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<News> example = Example.of(news, exampleMatcher);
        Pageable newsPage = PageRequest.of(0,5, Sort.by(Sort.Direction.DESC, "id"));
        Page<News> all = newsRepository.findAll(example,newsPage);
        Map<String, Object> data = new HashMap<>();
        data.put("totalPage", all.getTotalPages());
        data.put("total", all.getTotalElements());
        data.put("list", all.getContent());
        return data;
    }
    /**
     * 根据id获取新闻
     *
     * @param id
     * @return
     */
    @GetMapping("/oneNews")
    public News getOneNews(@RequestParam("ID") Integer id) {
        return fileService.getOneNews(id);
    }

    /**
     * 根据新闻标题获取新闻
     *
     * @param title
     * @return
     */
    @GetMapping("newsBytitle")
    public News getNewsByTitle(@RequestParam("title") String title) {
        return fileService.getNewsByTitle(title);
    }

    /**
     * 删除新闻
     *
     * @param id
     * @return
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin')")
    @DeleteMapping("/news")
    public String deleteNews(@RequestParam("ID") Integer id) {
        return fileService.deleteNews(id);
    }

    /**
     * 上传附件
     *
     * @param
     * @param res
     * @param category
     * @param id
     * @return
     * @throws IOException
     */
    @PreAuthorize("hasAnyRole('teacher', 'admin','student')")
    @PostMapping("/summitEnclosureFile")
    public Map<String, String> summitEnclosureFile(HttpServletRequest res,
                                                   @RequestParam("category") String category,
                                                   @RequestParam("id") Integer id) throws IOException {
        System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!");
        return fileService.summitEnclosureFile(res, category, id);
    }

    /**
     * 下载附件
     * @param request
     * @param response
     * @param category
     * @param fileName
     * @param id
     * @throws IOException
     */
    @GetMapping("/downloadEnclosureFile")
    public void downloadEnclosureFile(HttpServletRequest request,
                                      HttpServletResponse response,
                                      @RequestParam("category") String category,
                                      @RequestParam("filename") String fileName,
                                      @RequestParam("id") Integer id

    ) throws IOException{
        fileService.downloadEnclosureFile(category,id,fileName,request,response);
    }

}


